package dyyx.telnet;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.util.concurrent.DefaultThreadFactory;


public class TelnetServerInitializer extends ChannelInitializer<SocketChannel> {

    private static final StringDecoder DECODER = new StringDecoder();
    private static final StringEncoder ENCODER = new StringEncoder();

    private static final TelnetServerHandler SERVER_HANDLER = new TelnetServerHandler();

    private static final NioEventLoopGroup bizGroup = new NioEventLoopGroup(10,new DefaultThreadFactory("bizGroup"));
    // private static final GlobalTrafficShapingHandler trafficHandler = new GlobalTrafficShapingHandler(bizGroup, 30, 30);

    
    
    private static final boolean useBizGroup = false;
    static{
    	System.out.println("useBizGroup="+useBizGroup);
    }

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // pipeline.addLast(trafficHandler);

        // Add the text line codec combination first,
        pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        // the encoder and decoder are static as these are sharable
        pipeline.addLast(DECODER);
        pipeline.addLast(ENCODER);

        // and then business logic.
        // pipeline.addLast(SERVER_HANDLER);
        
        /*
        if(useBizGroup){
        	pipeline.addLast(bizGroup,SERVER_HANDLER);
            System.out.println("bizGroup.executorCount="+bizGroup.executorCount()+","+bizGroup);
        }else{
        	pipeline.addLast(SERVER_HANDLER);
        }
        */
        
        // 使用自定义业务线程池后 ，服务端 执行了 write ，但是 客户端无响应
        // 使用 writeAndFlush 后 ，已正常收到消息
        pipeline.addLast(new TelnetServerHandlerUseThreadPool());
    }
}
